import logging
import random

import requests
from fastapi import APIRouter, Request, Depends,BackgroundTasks
from fastapi.responses import PlainTextResponse,RedirectResponse

from sqlalchemy.orm import Session
from core.dependencies import get_sender_tools, get_redis_service
from core.logger import log
from db.mysql.customers import ChatMessageCreate
from db.pydantic.request.qw_wh import QWPathParams
from core.database import get_db
from services.call_task_service import get_call_task_service
from services.customers import save_chat_message
from services.qw_service import process_message
from services.redis_service import AsyncRedisService
from utils.WXBizJsonMsgCrypt import WXBizJsonMsgCrypt
from core.config import settings
from utils.qw_util import get_qw_access_token, get_kf_link, get_all_kf_id_list
from utils.result import Result

router = APIRouter()

from wechatpy.exceptions import InvalidSignatureException

logger = logging.getLogger("app.qw_router")

server = AsyncRedisService()

@router.get("/qw/webhook")
async def qw_webhook(msg_signature, timestamp, nonce, echostr):
    """
    企业微信回调
    :param token:
    :return:
    """

    try:
        log.info(f"加密的字符串:{echostr}")
        log.info(f"随机数:{nonce}")
        log.info(f"时间戳:{timestamp}")
        log.info(f"消息体签名:{msg_signature}")
        wxcpt = WXBizJsonMsgCrypt(settings.QW_TOKEN, settings.QW_SECRET, settings.QW_APP_ID)
        ret, sEchoStr = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr)
        if (ret != 0):
            print("ERR: VerifyURL ret: " + str(ret))
        else:
            print("done VerifyURL")
        log.info(f"解密后的明文消息内容1:{sEchoStr}")
        msg = sEchoStr.replace('"', "").replace('\n', "")
        log.info(f"解密后的明文消息内容2:{msg}")
        return PlainTextResponse(msg)
    except InvalidSignatureException:
        return "Invalid signature"

@router.post("/qw/webhook")
async def qw_webhook(req:Request,msg_signature,timestamp,nonce,background_tasks: BackgroundTasks,sender_tools = Depends(get_sender_tools),db: Session = Depends(get_db)):
    body = await req.body()
    # 记录接收到的原始数据
    log.info(f"接收到的原始消息内容: {body}")
    log.info(f"签名:{msg_signature}")
    log.info(f"随机数:{nonce}")
    log.info(f"时间戳:{timestamp}")
    qw_req = QWPathParams(msg_signature=msg_signature, timestamp=timestamp, nonce=nonce)
    await server.init_redis()

    # 先返回响应，然后在后台执行处理逻辑
    background_tasks.add_task(process_message, body, qw_req, server, sender_tools,db)
    return {"status": "ok"}




@router.get("/qw/kf/link")
async def qw_kf_link(phone:str,redis_sevice:AsyncRedisService=Depends(get_redis_service)):
    """
    获取客服链接需要传递参数
    :param access_token:
    :return:
    [
        {
            "open_kfid": "wkAJ2GCAAASSm4_FhToWMFea0xAFfd3Q",
            "name": "咨询客服",
            "avatar": "https://wework.qpic.cn/wwhead/duc2TvpEgSSjibPZlNR6chpx9W3dtd9Ogp8XEmSNKGa6uufMWn2239HUPuwIFoYYZ7Ph580FPvo8/0",
            "manage_privilege": false
        }
    ]
    """
    try:

        access_token = await redis_sevice.get_qw_access_token()
        if access_token is None:
            access_token = await get_qw_access_token()
        kf_list: list[dict] = await get_all_kf_id_list(access_token)
        kf = random.choice(kf_list)
        result = await get_kf_link(access_token=access_token, phone=phone, open_kfid=kf["open_kfid"])
        return Result.success(data=result)
    except Exception as e:
        log.error(f"获取客服链接时发生错误: {str(e)}")
        return Result.fail(msg=f"获取客服链接失败: {str(e)}")


@router.get("/qw/s/vN5x8")
async def aa():
    """
    获取客服列表
    :param access_token:
    :return:
    """
    links = ["https://work.weixin.qq.com/kfid/kfcf9e14a2d3b6d781b","https://work.weixin.qq.com/kfid/kfc7392c42cdf6ea96c"]
    link = random.choice(links)
    return RedirectResponse(url=link, status_code=302)


@router.post("/qw/{task_id}/complete")
async def complete_call_task(task_id: str,db:Session = Depends(get_db)):
    """
    完成通话任务
    参数: {
        task_id: string
    }
    返回: {
        message: string
    }
    """
    try:
        call_service = get_call_task_service()
        responses =await call_service.complete_task(task_id,db)
        return Result.success(data=responses)
    except Exception as e:
        return Result.fail(msg=str(e))


@router.post("/qw/chat/message")
async def save_chat_message_endpoint(
    message_data: ChatMessageCreate,
    redis_service: AsyncRedisService = Depends(get_redis_service)
):
    """
    保存聊天记录到Redis
    """
    try:
        # 调用服务层处理
        message_dict = message_data.model_dump(exclude_unset=True)
        result = await save_chat_message(message_dict, redis_service)
        return result
    except Exception as e:
        logger.exception(f"保存聊天记录时发生错误: {type(e).__name__}")
        return Result.fail(msg=f"保存聊天记录失败: {str(e)}")